﻿using System;
using System.Net;
using System.Runtime.Serialization.Json;
using Microsoft.Phone.Controls;
using MSH.Common.DAO.Results;
using WP7Client.Helpers;
using WP7Client.UserInterface.Pages;

namespace WP7Client.ServerManager
{
    /// <summary>
    /// Mode0 is voor vaste parameter aantal
    /// Mode1 is voor dynamische parameter aantal
    /// </summary>
    public enum HttpGetMode
    {
        Mode0 = 0,
        Mode1 = 1
    }

    public class HttpGet
    {
        public static Boolean LastGetWasSuccesfull = true;

        private String Url;
        private Type OTRType;
        public Object resultObject;

        public event EventHandler FinishedGet;

        /// <summary>
        /// Maakt een nieuwe HttpWebRequest aan voor een Get.
        /// </summary>
        /// <param name="url">Url van de methode</param>
        /// <param name="otrType">Het type van het object wat men terug verwacht.</param>
        /// <param name="mode">De gekozen HttpGetMode</param>
        public HttpGet(String url, Type otrType, HttpGetMode mode = HttpGetMode.Mode0)
        {
            this.Url = url;
            OTRType = otrType;
            HttpWebRequest req;
            if (mode == HttpGetMode.Mode1)
                req = HttpWebRequest.Create(new Uri(Url + "&token=" + Guid.NewGuid().ToString())) as HttpWebRequest;
            else
                req = HttpWebRequest.Create(new Uri(Url + "?token=" + Guid.NewGuid().ToString())) as HttpWebRequest;
            req.Method = "GET";
            req.AllowAutoRedirect = true;
            req.BeginGetResponse(req_ResponseCallback, req);
        }

        private void req_ResponseCallback(IAsyncResult result)
        {
            try
            {
                if (OTRType == null)
                    return;

                var req = result.AsyncState as HttpWebRequest;

                if (req.HaveResponse)
                {
                    using (var resp = req.EndGetResponse(result))
                    {
                        DataContractJsonSerializer ser = new DataContractJsonSerializer(OTRType);
                        resultObject = ser.ReadObject(resp.GetResponseStream());
                        resp.Close();
                        ControllerHelper.OverviewController.IsConnected = true;
                        if (FinishedGet != null)
                            FinishedGet.Invoke(this, null);
                        if (resultObject is BaseResult && (resultObject as BaseResult).TokenValidationResult == MSH.Common.Classes.TokenValidationResultEnum.Invalid)
                        {
                            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                            {
                                ControllerHelper.ConversationsController.Save();
                                IsolatedStorageHelper.DeleteData("token");
                                IsolatedStorageHelper.DeleteData("username");
                                ControllerHelper.Shutdown();
                                NavigationHelper.CanShutdown = true;
                                NavigationHelper.NavigateTo("/UserInterface/Pages/LoginPage.xaml");
                            });
                        }
                    }
                }
                else
                {
                    //bier drinken
                }
            }
            catch (Exception ex)
            {
                if (FinishedGet != null)
                    FinishedGet.Invoke(this, null);

                if (ControllerHelper.OverviewController != null && ControllerHelper.OverviewController.IsConnected)
                {
                    //GlobalHelper.ShowMessage("Connection error", "Service currently unavailable.");
                    if(ControllerHelper.OverviewController != null)
                        ControllerHelper.OverviewController.IsConnected = false;
                }
            }
        }
    }
}
